﻿
Namespace bithelper
    Public Module bithelper
        Public ReadOnly jump1() As Byte = {128, 64, 32, 16, 8, 4, 2, 1}
        Public ReadOnly jump0() As Byte = {127, 191, 223, 239, 247, 251, 253, 254}

        Public Function getbit(ByVal b As Byte, ByVal index As Byte) As Boolean
            Return (b And jump1(index))
        End Function

        Public Sub setbit(ByRef b As Byte, ByVal index As Byte, Optional ByVal value As Boolean = True)
            If value Then
                b = (b Or jump1(index))
            Else
                b = (b And jump0(index))
            End If
        End Sub

        Private Function _1countImpl(ByVal b As UInt64) As Byte
            Dim i As Byte = 0
            While b > 0
                b = b And (b - 1)
                i += 1
            End While

            Return i
        End Function

        Public Function _1count(ByVal b As Int64) As Byte
            If b < 0 Then
                Return _1countImpl(maxInt64 + b + 1) + 1
            Else
                Return _1countImpl(b)
            End If
        End Function

        Public Function onecount(ByVal b As Int64) As Byte
            Return _1count(b)
        End Function
    End Module
End Namespace
